<?php
// 本类由系统自动生成，仅供测试用途
namespace Admin\Controller;
use Think\Controller;
use Redis;
class LoginController extends Controller {
    /**
     * 登录页视图
     */
    public function index(){
        $this->display('login');
    }
    /**阿里云测试短信 */
    public function cesduanx(){
        $phone = "17783641562";
        $code  = "123456";
        // $alisms = new \Common\Model\Alisms();
        $result = aliyunCodeVerify($phone,$code);
        print_r($result);die;
    }
    /**
     * 发送验证码
     * @return [type] [description]
     */
    public  function  login_code() {
        $mode = M('admin');

        if(session('?lampzuo_id')){
            echo json_encode(['error'=>'4','message'=>'当前已经是登陆状态！']);return;
        }

    	$mobilephone = I('post.phone_num');

        $userdata = $mode->where(['tel'=>trim($mobilephone)])->field('tel,status')->find();

        if(!$userdata){
            echo json_encode(['error'=>'3','message'=>'该手机号不存在登陆权限！']);return;
        }else if(!preg_match("/1[345678]{1}\d{9}$/",$mobilephone)){
            echo json_encode(['error'=>'1','message'=>'请输入正确的手机号！']);return;
        }else if($userdata['status'] == 1){
            echo json_encode(['error'=>'3','message'=>'对不起，您的账号已被禁止登陆优优车管理系统！']);return;
        }

        $time = time();

        $codetimeout = session('codetime');

        if(!empty($codetimeout)){
            $timeout = $time-$codetimeout;

            if($timeout<=60){
                 echo json_encode(['error'=>'2','message'=>'请勿频繁操作！']);return;
            }
        }

        $checkcode = randomkeys(4,1);

        session('code',$checkcode);

        session('codetime',$time);

		// $result = messagelog($mobilephone,$checkcode,$userdata['id']);
        $result = aliyunCodeVerify($mobilephone,$checkcode);
        echo json_encode(['success'=>'OK','message'=>$result],true);
    }

    /**
     * 手机登录
     */
    public function login() {
        $post = I('post.');

    	$mode = M('admin');

        $time   = time();
        
        $result = $mode->where(array('tel'=>$post['mobilephone']))->find();

        $token = $result['token'];
        // 创建签名
        if(empty($token)&&$result) {
            do{
                $token = randomkeys('5');
            }while($mode->where(array('token'=>$token))->find());

            $save_data['token'] = $token;
        }
        // 生成签名密钥
        $pass = md5($token.$time);
        // 客户端可接收的数据
        $respnose = [
            'uid'=>$result['id'],
            'name'=>$result['name'],
            'position'=>$result['position'],
            'phone'=>$result['tel']
        ];
        // 检测不同的登录方法进行登录
        if(empty($post['checkcode'])&&!empty($post['JinDouCheToken'])) {
            // 是否已经是登录状态
            if(session('?lampzuo_id')) {
                echo json_encode(['error'=>'7','message'=>'当前已经为登陆状态！','data'=>$respnose]);return;
            }
            $pass_prev = md5($token.$result['prevlogintime']);
            // 数据库中的密钥与客户端的密钥参数对比
            if(trim($post['JinDouCheToken'])!=$pass_prev){
                echo json_encode(['error'=>'5','message'=>'您的密钥参数不正确！']);return;
            }
        }else if(empty($post['JinDouCheToken'])&&!empty($post['checkcode'])) {
            // 是否已经是登录状态
            if(session('?lampzuo_id')){
                echo json_encode(['error'=>'7','message'=>'当前已经为登陆状态！','data'=>$respnose]);return;
            }
            $codetimeout = session('codetime');
            $code = session('code');
            // 计算时间差
            $timeout = $time-$codetimeout;
            $phonetel = ['16600220523','15334509852','18811410626','18310072979','17783641562','13672122967','18920347580','13284002682','13552992685','15941273717'];
            // if(!in_array($respnose['phone'],$phonetel)){
            //     // 对比客户端输入的验证码
            //     if(trim($post['checkcode'])!=$code) {
            //         echo json_encode(['error'=>'2','message'=>'验证码不正确，请确认！']);return;
            //     }
            //     // // 验证码仅在5分钟内有效
            //     if($timeout>=300) {
            //          echo json_encode(['error'=>'1','message'=>'验证码已过期，请重新输入验证码！']);return;
            //     }
            // }
        }else{
            echo json_encode(['error'=>'6','message'=>'请输入验证码！']);return;
        }
        // 排除风控人员、财务人员及其他
        $auth = ['1','2','3','4','1100','301','9','101'];
        if(!in_array($result['position'], $auth)) { 
            echo json_encode(['error'=>'3','message'=>'您的账号权限无法登陆本系统！']);return;
        }
        // 禁止以禁用的账号登录
        if($result['status'] == 1) { 
            echo json_encode(['error'=>'4','message'=>'对不起，您的账号已被禁止登陆优优车管理系统！']);return;
        }
        // 记录登录时间
        $save_data['prevlogintime'] = $time;
        // 记录当前的登录ip
        $save_data['prevlog_ipv4'] = $_SERVER['REMOTE_ADDR'];
        // 写入登录记录
        $save_result = $mode->where('id='.$result['id'])->save($save_data);

        if($save_result){
            session('lampzuo_id',$result['id']);

            session('lampzuo_usernum',$result['usernum']);

            echo json_encode(['success'=>'OK','message'=>'登录成功！','JinDouCheToken'=>$pass,'data'=>$respnose]);
        }else{
            echo json_encode(['error'=>'8','message'=>'信息记录有误，登录失败！请稍后再试。']);
        }
    }

    /**
     * 电脑端登录 
     */
    public function LoginComputer() {
        $post = I('post.');

        $status_option = ['1','2','3'];

        $mode = M('admin');

        $time   = time();

        $result = $mode->where(array('tel'=>$post['mobilephone']))->find();

        $token = $result['token'];
        // 生成新的token签名
        if(empty($token)&&$result){
            do{
                $token = randomkeys('5');
            }while($mode->where(array('token'=>$token))->find());
            
            $save_data['token'] = $token;
        }
        // 将拼接后的密钥交给客户端
        $pass = md5($token.$time); 
        // 用户可见的参数
        $respnose = [
            'uid'=>$result['id'],
            'name'=>$result['name'],
            'position'=>$result['position'],
            'phone'=>$result['tel']
        ];
        
        if(session('?lampzuo_id')){
            echo json_encode(['error'=>'7','message'=>'当前已经为登陆状态！','data'=>$respnose],true);return;
        }
        
        if(empty($post['checkcode'])&&!empty($post['JinDouCheToken'])){
            // 记录的签名和用户的密钥对比
            $pass_prev = md5($token.$result['prevlogintime']);
            
            if(trim($post['JinDouCheToken'])!=$pass_prev){
                echo json_encode(['error'=>'5','message'=>'您的账号已在其他设备登录！']);return;
            }
        }else if(empty($post['JinDouCheToken'])&&!empty($post['checkcode'])&&$post['status']==1){
            $codetimeout = session('codetime');

            $code = session('code');

            $timeout = $time-$codetimeout;
            $phonetel = ['16600220523','15334509852','18811410626','18310072979','17783641562','18920347580','13672122967','13284002682','13552992685','15941273717'];
            // if(!in_array($respnose['phone'], $phonetel)){
            //     // 对比客户端输入的验证码
            //     if(trim($post['checkcode'])!=$code) {
            //         echo json_encode(['error'=>'2','message'=>'验证码不正确，请确认！']);return;
            //     }
            //     // // 验证码仅在5分钟内有效
            //     if($timeout>=300) {
            //          echo json_encode(['error'=>'1','message'=>'验证码已过期，请重新输入验证码！']);return;
            //     }
                
            // }
            

        }else if(!empty($post['password'])&&$post['status']==2){
            if(empty($result['password'])){
                echo json_encode(['error'=>'6','message'=>'抱歉！您的账号还没有设置过密码。']);return;
            }

            $userpass = md5(trim($post['password']));

            if($userpass!==$result['password']){
                echo json_encode(['error'=>'6','message'=>'抱歉！您输入的密码不正确。']);return;
            }
        }else{
            echo json_encode(['error'=>'6','message'=>'请输入验证码或密码来登录。']);return;
        }

        if(!in_array($post['status'],$status_option)){
            echo json_encode(['error'=>'5','message'=>'无法识别您的登录方法。']);return;
        }
        // 风控人员、财务人员、风控人员（仅渠道）、库存人员、出纳员、账号管理员
        $auth = ['5','501','502','503','6','7','8','9','901','10','1101'];
        if($result['tel'] != "18310072979"){
            if(!in_array($result['position'], $auth)){
                echo json_encode(['error'=>'3','message'=>'您的账号权限无法登陆本系统！']);return;
            }
        }
        if($result['status'] == 1){
            echo json_encode(['error'=>'4','message'=>'对不起，您的账号已被禁止登陆优优车管理系统！']);return;
        }
        // 记录登录时间
        $save_data['prevlogintime'] = $time;
        // 记录当前的登录ip
        $save_data['prevlog_ipv4'] = $_SERVER['REMOTE_ADDR'];
        // 写入登录记录
        $save_result = $mode->where('id='.$result['id'])->save($save_data);
        
        if($save_result){
            session('lampzuo_id',$result['id']);
            
            session('lampzuo_usernum',$result['usernum']);
            
            if(empty($result['password'])&&$post['status']==1){
                echo json_encode([
                    'success'=>'OK','message'=>'登录成功！',
                    'JinDouCheToken'=>$pass,'data'=>$respnose,
                    'password'=>'1'
                ],true);

                return true;
            }

            echo json_encode([
                'success'=>'OK','message'=>'登录成功！',
                'JinDouCheToken'=>$pass,'data'=>$respnose
            ],true);

            return true;
        }else{
            if($post['status']=='3'){
                echo json_encode(['error'=>'8','message'=>'信息获取失败，请手动登录！']);
            }else{
                echo json_encode(['error'=>'8','message'=>'信息记录有误，登录失败！请重新登录。']);
            }
        }
    }

    /**
     * 设置密码
     */
    public function SetPasswd() {
        $meid = $this->Islogin();

        $post = I('post.');

        $reg = "/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/";

        if(!preg_match($reg,$post['password_set'])){ 
            echo json_encode(['error'=>'1','message'=>"密码格式：6-10位，需包含字母、数字的组合。请确认！"]);return;
        }

        $password = md5($post['password_set']);

        $save_res = M('admin')->where('id='.$meid)->save(['password'=>$password]);

        if($save_res){
            echo json_encode(['success'=>'OK','message'=>"成功！"]);return;
        }else{
            echo json_encode(['error'=>'2','message'=>"密码设置失败！"]);return;
        }
    }

    /**
     * 手机端退出登录
     */
    public function LogoutPhone() {
        // logout方法在Controller控制器中
        $this->logout();

        echo json_encode(['success'=>'OK','message'=>'登陆状态已改变！']);
    }

    /**
     * 电脑端退出登陆
     */
    public function logoutComputer() {
        // logout方法在Controller控制器中
        $this->logout();

        $weburl = C('WEBURL');

        header("Location: {$weburl}admin/login");
    }

    /**
     * 账号管理界面
     */
    public function AddAdmin() {
        $this->Islogin('1101');

        $data = M('admin')->where('position<1000')->select();

        $citydata = D('city')->CityGetAll(false,true);

        $zhiwei = [
            '1'=>'销售顾问','2'=>'手续办理员',
            '3'=>'城市经理人','4'=>'省总',
            '5'=>'风控人员','6'=>'财务人员',
            '7'=>'二级风控人员','501' => '风控经理',
            '502' => '风控副总','10' => '信息管理员',
            '1101'=>'账号管理员'
        ];

        $this->assign('admins',$data);

        $this->assign('citydata',$citydata);
        
        $this->assign('zhiwei',$zhiwei);

        $this->display('add');
    }

    /**
     * 添加管理员
     */
    public function InsertAdmin() {
        $this->Islogin('1101');

        $post = I('post.');

        $time = time();

        $username = trim($post['username']);

        $phone = trim($post['phone']);

        $auth = trim($post['auth']);

        $province = trim($post['province']);

        $cityid = trim($post['city']);

        $usernum = trim($post['usernum']);

        $remarks = trim($post['remarks']);

        $admin_db = D('admin');
        // $enddata = $admin_db->order('usernum desc')->limit(1)->find();
        // if($enddata){
        //     $num = $enddata['usernum']+1;
        // }else{
        //     $num = '10001';
        // }
        $admindata = $admin_db->where('tel='.$phone)->find();

        $nun = $admin_db->where(array('usernum'=>$usernum))->find();

        if($nun){
            echo json_encode(['error'=>'2','message'=>'员工编号已存在']);return;
        }

        if($admindata){
            echo json_encode(['error'=>'2','message'=>'该手机号已经存在！']);return;
        }

        $InsertData = [
            'usernum'=>$usernum,
            'name'=>$username,
            'tel'=>$phone,
            'position'=>$auth,
            'status'=>'1',
            'cityid'=>$cityid,
            'provinceid'=>$province,
            'remarks'=>$province,
            'insert_time'=>$time,
        ];

        $res = $admin_db->add($InsertData);

        if($res){
            echo json_encode(['success'=>'OK','message'=>'添加成功！']);
            return;
        }else{
            echo json_encode(['error'=>'1','message'=>'添加失败请联系开发人员！']);
            return;
        }
    }

    /**
     * 修改管理员信息
     */
    public function EditAdmin() {
        $this->Islogin('1101');

        $post = I('post.');

        $time = time();

        @$phone = trim($post['phone']);

        $auth = trim($post['auth']);

        $province = trim($post['province']);

        $cityid = trim($post['city']);

        $userid = trim($post['userid']);

        $admin_db = D('admin');

        if(!empty($phone)){
            $admindata = $admin_db->where('tel='.$phone)->find();

            if($admindata){
                echo json_encode(['error'=>'2','message'=>'该手机号已经存在！']);
                return;
            }

            $InsertData['tel'] = $phone;
        }
        
        $InsertData['position'] = $auth;

        $InsertData['cityid'] = $cityid;

        $InsertData['provinceid'] = $province;

        $res = $admin_db->where('id='.$userid)->save($InsertData);

        if($res){
            echo json_encode(['success'=>'OK','message'=>'修改成功！']);return;
        }else{
            echo json_encode(['error'=>'1','message'=>'修改失败请联系开发人员！']);return;
        }
    }
    
    /**
     * 所有城市经理人
     */
    public function CsManager() {
        $meid = $this->Islogin();
        $admin_mdb =  M('admin');
        $wayuser_mdb =  M('wayuser');
        $city_db = D('city');
        $medata = $admin_mdb->where('id='.$meid)->find();
        switch ($medata['position']) {
            // 全国权限账号条件
            case '1100':
                $where_city = '';
                if(!empty(I('get.province'))){
                    $where_city = ' and provinceid='.I('get.province');
                }
                $response['provinceid'] = $city_db->CityGetAll(false,false,false);
                $iscs = false;
                $response['position'] = 1100;
                break;
            // 省总权限条件
            case '4':
                $where_city = ' and provinceid='.$medata['provinceid'];
                $iscs = false;
                $response['position'] = 4;
                break;
            // 城市经理
            case '3':
                $where_city = ' and pid='.$medata['id'];
                $iscs = true;
                $response['position'] = 3;
                break;
            default:
                exit(json_encode(['error'=>'1','message'=>'您的账号权限不涉及本功能！']));
        }
        // 筛选时间段
        // 本月开始的时间戳
        $BeginDate = strtotime(date("Y-m-01"));
        // 本月结束的时间戳
        $EndDate = mktime(0, 0, 0,date('m')+1,1)-1;
        // 今日开始的时间戳
        $Beginday = strtotime(date('Y-m-d 00:00:00'));
        // 今日结束的时间戳
        $EndDay = strtotime(date('Y-m-d 23:59:59'));
        // $timesql = ' and create_time>='.$BeginDate.' and create_time<='.$EndDate;
        $timesql = '';
        if($medata['position']==3){
            $Gwdata = $admin_mdb
            ->where('pid='.$medata['id'].' and position=1'.$this->istest['testsql'])
            ->field('id,name,tel')
            ->select();
            for ($s=0; $s < count($Gwdata); $s++) { 
                $manager['channel_count'] +=  $Gwdata[$s]['channel_count'] = $wayuser_mdb
                ->where('admin_id='.$Gwdata[$s]['id'].$timesql)
                ->count();
                $manager['channel_create_count'] += $Gwdata[$s]['channel_create_count'] = $wayuser_mdb
                ->where('status>=0 and status<=1 and admin_id='.$Gwdata[$s]['id'].$timesql)
                ->count();
                $manager['channel_success_count'] += $Gwdata[$s]['channel_success_count'] = $wayuser_mdb
                ->where('status=2 and admin_id='.$Gwdata[$s]['id'].$timesql)
                ->count();
                $manager['channel_refuse_count'] += $Gwdata[$s]['channel_refuse_count'] = $wayuser_mdb
                ->where('status=-1 and admin_id='.$Gwdata[$s]['id'].$timesql)
                ->count();
                $manager['channel_back_count'] += $Gwdata[$s]['channel_back_count'] = $wayuser_mdb
                ->where('status=-2 and admin_id='.$Gwdata[$s]['id'].$timesql)
                ->count();
            }
            $response['success'] = 'OK';
            // 城市经理的个人信息
            $response['manager'] = $manager;
            // GW的个人信息
            $response['Gwdata'] = $Gwdata;
            // GW的渠道数据统计
            $response['GWcount'] = $gwcount;
            exit(json_encode($response,true));
        }
        // 所有城市经理
        $manager = $admin_mdb
        ->where('position=3'.$where_city.$this->istest['testsql'])
        ->select();
        $channelcount = [];
        // 城市经理总数
        $cscount = count($manager);
        $gwcount = 0;
        for ($i=0; $i <  $cscount; $i++) { 
            // 城市经理下属的所有GW
            $Gwdata = $admin_mdb
            ->where('pid='.$manager[$i]['id'].' and position=1'.$this->istest['testsql'])
            ->field('id,name,tel')
            ->select();
            // 统计渠道数据
            if(!$Gwdata){
                $manager[$i]['channelcount'] = 0;
                $manager[$i]['channel_create_count'] = 0;
                $manager[$i]['channel_success_count'] = 0;
                $manager[$i]['channel_refuse_count'] = 0;
                $manager[$i]['channel_back_count'] = 0;
                $manager[$i]['GWcount'] = 0;
                $manager[$i]['GWlist'] = [];
            }else{
                $manager[$i]['GWcount'] = count($Gwdata);
                $Gwdataids = implode(',',array_column($Gwdata,'id'));
                $manager[$i]['channelcount'] = $wayuser_mdb
                ->where('admin_id in('.$Gwdataids.')'.$timesql)
                ->count();
                for ($s=0; $s < count($Gwdata); $s++) { 
                    $Gwdata[$s]['channel_count'] = $wayuser_mdb
                    ->where('admin_id='.$Gwdata[$s]['id'].$timesql)
                    ->count();
                    $manager[$i]['channel_create_count'] += $Gwdata[$s]['channel_create_count'] = $wayuser_mdb
                    ->where('status>=0 and status<=1 and admin_id='.$Gwdata[$s]['id'].$timesql)
                    ->count();
                    $manager[$i]['channel_success_count'] += $Gwdata[$s]['channel_success_count'] = $wayuser_mdb
                    ->where('status=2 and admin_id='.$Gwdata[$s]['id'].$timesql)
                    ->count();
                    $manager[$i]['channel_refuse_count'] += $Gwdata[$s]['channel_refuse_count'] = $wayuser_mdb
                    ->where('status=-1 and admin_id='.$Gwdata[$s]['id'].$timesql)
                    ->count();
                    $manager[$i]['channel_back_count'] += $Gwdata[$s]['channel_back_count'] = $wayuser_mdb
                    ->where('status=-2 and admin_id='.$Gwdata[$s]['id'].$timesql)
                    ->count();
                }
                $manager[$i]['GWlist'] = $Gwdata;
            }
            $channelcount['channelcount'] += $manager[$i]['channelcount'];
            $channelcount['channel_create_count'] += $manager[$i]['channel_create_count'];
            $channelcount['channel_success_count'] += $manager[$i]['channel_success_count'];
            $channelcount['channel_refuse_count'] += $manager[$i]['channel_refuse_count'];
            $channelcount['channel_back_count'] += $manager[$i]['channel_back_count'];
        }
        $response['success'] = 'OK';
        // 城市经理的个人信息
        $response['manager'] = $manager;
        // GW的渠道数据统计
        $response['GWcount'] = $gwcount;
        // 全部总渠道统计
        $response['channelcount'] = $channelcount;
        exit(json_encode($response,true));
    }

    /**
     * 获取地区信息
     */
    public function region() {
        $city_db = D('city');

        $data = $city_db->CityGetAll();

        echo json_encode(['success'=>'OK','data'=>$data]);
    }

    /**
     * 判断手机号是否存在
     */
    public function ResetPassword(){
        $data = I('post.');
        $time = time();
        if($data['judge'] =="judge"){
           $res = $this->VerificationCoed($data);
           $this->ajaxReturn($res);
        }elseif($data['judge'] =="acceptcoed"){
            $res = $this->VerificationCoed($data);
            if(!$res['success'] == "OK"){
                $this->ajaxReturn($res);
            }
            $codetimeout = session('codetime_phone');
            if(!empty($codetimeout)){
                $timeout = $time-$codetimeout;
                if($timeout<=60){
                     $this->ajaxReturn(['success'=>'ERROR','message'=>'请勿频繁操作！']);return;
                }
            }
            $checkcode = randomkeys(4,1);
            session('code_phone',$checkcode);
            session('codetime_phone',$time);
            // $result = messagelog($data['phone'],$checkcode,"1");
            $result = aliyunCodeVerify($data['phone'],$checkcode);
            echo json_encode(['success'=>'OK','message'=>$result],true);
        }elseif($data['judge'] =="obtaincoed"){
            $codetimeout = session('codetime_phone');
            $code = session('code_phone');
            // 计算时间差
            $timeout = $time-$codetimeout;
            // 对比客户端输入的验证码
            if(trim($data['phone_coed'])!=$code) {
                echo json_encode(['success'=>'ERROR','message'=>'验证码不正确，请确认！']);return;
            }
            // // 验证码仅在5分钟内有效
            if($timeout>=300) {
                 echo json_encode(['success'=>'ERROR','message'=>'验证码已过期，请重新输入验证码！']);return;
            }
            $this->ajaxReturn(['success'=>"OK",'message'=>"验证成功"]);
        }elseif($data['judge'] =="passtype"){
            if($data['passwordphone'] != $data['endpasswordphone']){
                echo   json_encode(["success"=>"ERROR","message"=>"输入密码不一致"]);return;
            }
            $admin = M('admin');
            $res = $admin->where("tel=".$data['phone'])->find();
            if(!$res){
                echo   json_encode(["success"=>"ERROR","message"=>"对不起你手机号有误,请重新验证"]);return;
            }
            $md5 = md5(trim($data['passwordphone']));
            $addsave = $admin -> where("id =".$res['id'])->save(array('password'=>$md5));
            if($addsave){
                echo   json_encode(['success'=>"OK",'message'=>"验证成功"]); return;
            }else{
                echo   json_encode(['success'=>"ERROR",'message'=>"您的新密码与旧密码重复"]); return;

            }
        }
    }

    public  function VerificationCoed($data){
        $admin = M('admin');
        $res = $admin->where("tel = ".$data['phone'])->find();
        if(!$res){
           return  ["success"=>"ERROR","message"=>"对不起,你手机号有误,请重新验证"];
        }
        // 排除风控人员、财务人员及其他
        $auth = ['1','2','3','4','1100'];
        if(in_array($res['position'], $auth)) { 
           return  ['success'=>'ERROR','message'=>'您的账号权限无法修改密码！'];
        }elseif($res['status'] == "1"){
            return  ['success'=>'ERROR','message'=>'对不起，您的账号已被禁止登陆优优车管理系统！'];
        }
        return  ['success'=>"OK",'message'=>"验证成功"];
    }
    
}

